<template>
  <view class="mine-page">
    <view class="profile">
      <image class="avatar" :src="avatarUrl" mode="aspectFill" />
      <view class="info">
        <text class="nickname">{{ nickname }}</text>
        <text class="uid">ID: {{ userId }}</text>
        <text class="login-status" v-if="userId !== '0'">已登录</text>
        <text class="login-status" v-else>未登录</text>
      </view>
      <button class="edit-btn" @click="editProfile">{{ userId === '0' ? '登录' : '编辑' }}</button>
    </view>

    <view class="stats">
      <view class="stat-item" @click="goTo('favorites')">
        <text class="num">{{ stats.favorites }}</text>
        <text class="label">收藏</text>
      </view>
      <view class="stat-item" @click="goTo('history')">
        <text class="num">{{ stats.history }}</text>
        <text class="label">历史</text>
      </view>
      <view class="stat-item" @click="goTo('downloads')">
        <text class="num">{{ stats.downloads }}</text>
        <text class="label">下载</text>
      </view>
    </view>

    <!-- 最近播放 -->
    <view class="recent-section" v-if="userId !== '0' && recentHistory.length > 0">
      <view class="section-header">
        <text class="section-title">最近播放</text>
        <text class="more-btn" @click="goTo('history')">查看全部</text>
      </view>
      <scroll-view class="recent-list" scroll-x>
        <view class="recent-item" v-for="(item, index) in recentHistory" :key="index">
          <view class="recent-content" @click="goToPlayer(item)">
            <image class="recent-cover" :src="item.cover" mode="aspectFill" />
            <view class="recent-play-overlay" v-if="isPlaying && currentPlayingId === item.id">
              <image class="recent-play-icon" src="/static/stop.png" mode="aspectFit"></image>
            </view>
            <text class="recent-title">{{ item.title }}</text>
            <text class="recent-artist">{{ item.artist }}</text>
          </view>
          <button class="recent-delete" @click="deleteRecentHistory(item, index)">
            <image class="delete-icon" src="/static/delete.png" mode="aspectFit"></image>
          </button>
        </view>
      </scroll-view>
    </view>

    <view class="section">
      <view class="cell" @click="goTo('vip')">
        <text class="cell-text">会员中心</text>
        <uni-icons type="arrowright" size="18" color="#999" />
      </view>
      <view class="cell" @click="goTo('settings')">
        <text class="cell-text">设置</text>
        <uni-icons type="arrowright" size="18" color="#999" />
      </view>
      <view class="cell" @click="goTo('feedback')">
        <text class="cell-text">意见反馈</text>
        <uni-icons type="arrowright" size="18" color="#999" />
      </view>
      <view class="cell" @click="goTo('about')">
        <text class="cell-text">关于</text>
        <uni-icons type="arrowright" size="18" color="#999" />
      </view>
    </view>

    <view class="logout-wrapper">
      <button class="logout-btn" @click="logout">退出登录</button>
    </view>
  </view>
  
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'

const API_BASE_URL = 'http://localhost:3001'
const avatarUrl = ref('https://ai-public.mastergo.com/ai/img_res/4f8c61af426b6e29d3c0f5ce2f9e1f66.jpg')
const nickname = ref('未登录用户')
const userId = ref('0')

const stats = ref({ favorites: 0, history: 0, downloads: 0 })
const recentHistory = ref<any[]>([])
const isPlaying = ref(false)
const currentPlayingId = ref<number | null>(null)

const editProfile = () => {
  if (userId.value === '0') return uni.navigateTo({ url: '/pages/auth/login' })
  uni.navigateTo({ url: '/pages/mine/profile' })
}

const goTo = (name: string) => {
  if (name === 'favorites') {
    if (userId.value === '0') return uni.navigateTo({ url: '/pages/auth/login' })
    uni.navigateTo({ url: `/pages/mine/favorites?userId=${userId.value}` })
    return
  }
  if (name === 'history') {
    if (userId.value === '0') return uni.navigateTo({ url: '/pages/auth/login' })
    uni.navigateTo({ url: `/pages/mine/history?userId=${userId.value}` })
    return
  }
  uni.showToast({ title: `跳转到 ${name}`, icon: 'none' })
}

const logout = () => {
  if (userId.value === '0') return uni.showToast({ title: '未登录', icon: 'none' })
  uni.showModal({
    title: '确认退出',
    content: '确定要退出登录吗？',
    success: (res) => {
      if (res.confirm) {
        // 清除本地存储
        uni.removeStorageSync('user')
        // 重置用户信息
        userId.value = '0'
        nickname.value = '未登录用户'
        avatarUrl.value = 'https://ai-public.mastergo.com/ai/img_res/4f8c61af426b6e29d3c0f5ce2f9e1f66.jpg'
        stats.value = { favorites: 0, history: 0, downloads: 0 }
        uni.showToast({ title: '已退出', icon: 'success' })
        // 延迟刷新页面，确保状态更新
        setTimeout(() => {
          loadProfile()
        }, 500)
      }
    }
  })
}

// 简易本地"登录态"：使用本地存储保存用户
const loadProfile = async () => {
  const localUser = uni.getStorageSync('user')
  if (localUser && localUser.id) {
    userId.value = String(localUser.id)
    nickname.value = localUser.nickname || localUser.username || '用户'
    // 确保头像URL正确显示
    avatarUrl.value = localUser.avatar || 'https://ai-public.mastergo.com/ai/img_res/4f8c61af426b6e29d3c0f5ce2f9e1f66.jpg'
    await fetchStats()
    await fetchRecentHistory()
    
    // 如果本地头像为空，尝试从服务器获取最新信息
    if (!localUser.avatar) {
      try {
        const res = await uni.request({ url: `${API_BASE_URL}/api/users/${localUser.id}`, method: 'GET' })
        const serverUser = res?.data as any
        if (serverUser && serverUser.avatar) {
          avatarUrl.value = serverUser.avatar
          // 更新本地存储
          const updatedUser = { ...localUser, avatar: serverUser.avatar }
          uni.setStorageSync('user', updatedUser)
        }
      } catch {}
    }
  } else {
    userId.value = '0'
    nickname.value = '未登录用户'
    avatarUrl.value = 'https://ai-public.mastergo.com/ai/img_res/4f8c61af426b6e29d3c0f5ce2f9e1f66.jpg'
    stats.value = { favorites: 0, history: 0, downloads: 0 }
  }
}

const fetchStats = async () => {
  if (userId.value === '0') return
  try {
    const res = await uni.request({ url: `${API_BASE_URL}/api/users/${userId.value}/stats`, method: 'GET' })
    const data = res?.data as any
    if (data) {
      stats.value = {
        favorites: Number(data.favorites) || 0,
        history: Number(data.history) || 0,
        downloads: Number(data.downloads) || 0
      }
    }
  } catch (err) {
    console.log('获取统计数据失败:', err)
    stats.value = { favorites: 0, history: 0, downloads: 0 }
  }
}

const fetchRecentHistory = async () => {
  if (userId.value === '0') return
  try {
    const res = await uni.request({ url: `${API_BASE_URL}/api/users/${userId.value}/history`, method: 'GET' })
    const data = res?.data as any
    if (data && Array.isArray(data.items)) {
      // 只取最近5条记录
      recentHistory.value = data.items.slice(0, 5).map((item: any) => ({
        id: item.music_id,
        title: item.title,
        artist: item.artist,
        cover: item.cover,
        play_time: item.play_time
      }))
    }
  } catch (err) {
    console.log('获取最近播放历史失败:', err)
    recentHistory.value = []
  }
}

const playMusic = (item: any) => {
  // 这里可以添加播放音乐的逻辑
  console.log('播放音乐:', item.title)
  uni.showToast({ title: `播放: ${item.title}`, icon: 'none' })
}

const goToPlayer = (item: any) => {
  // 跳转到播放页面
  uni.navigateTo({
    url: `/pages/player/index?song=${encodeURIComponent(JSON.stringify(item))}`
  })
}

const togglePlayMusic = (item: any) => {
  if (currentPlayingId.value === item.id && isPlaying.value) {
    // 如果当前正在播放这首歌曲，则暂停
    isPlaying.value = false
    currentPlayingId.value = null
    console.log('暂停音乐:', item.title)
    uni.showToast({ title: `暂停: ${item.title}`, icon: 'none' })
  } else {
    // 播放新歌曲或继续播放
    isPlaying.value = true
    currentPlayingId.value = item.id
    console.log('播放音乐:', item.title)
    uni.showToast({ title: `播放: ${item.title}`, icon: 'none' })
  }
  
  // 跳转到播放页面
  uni.navigateTo({
    url: `/pages/player/index?song=${encodeURIComponent(JSON.stringify(item))}`
  })
}

const deleteRecentHistory = async (item: any, index: number) => {
  uni.showModal({
    title: '确认删除',
    content: `确定要删除"${item.title}"的播放记录吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          await uni.request({
            url: `${API_BASE_URL}/api/users/${userId.value}/history/${item.id}`,
            method: 'DELETE'
          })
          // 从最近播放列表中移除该项
          recentHistory.value.splice(index, 1)
          // 更新统计数据
          stats.value.history = Math.max(0, stats.value.history - 1)
          uni.showToast({ title: '删除成功', icon: 'success' })
        } catch (err) {
          console.log('删除播放历史失败:', err)
          uni.showToast({ title: '删除失败', icon: 'none' })
        }
      }
    }
  })
}

onLoad(() => {
  loadProfile()
})

// 监听页面显示，更新用户信息
onShow(() => {
  loadProfile()
})
</script>

<style>
.mine-page {
  min-height: 100vh;
  background: #f7f8fa;
}

.profile {
  display: flex;
  align-items: center;
  padding: 30rpx;
  background: #fff;
}

.avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 60rpx;
  margin-right: 20rpx;
}

.info {
  display: flex;
  flex-direction: column;
  flex: 1;
}

.nickname {
  font-size: 32rpx;
  color: #333;
  font-weight: 600;
}

.uid {
  margin-top: 8rpx;
  font-size: 24rpx;
  color: #999;
}

.login-status {
  margin-top: 6rpx;
  font-size: 22rpx;
  color: #007AFF;
}

.edit-btn {
  padding: 12rpx 24rpx;
  font-size: 24rpx;
  color: #333;
  background: #f2f3f5;
  border: none;
  border-radius: 30rpx;
}

.stats {
  display: flex;
  justify-content: space-around;
  background: #fff;
  margin-top: 20rpx;
  padding: 20rpx 0;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.num {
  font-size: 32rpx;
  color: #333;
  font-weight: 600;
}

.label {
  margin-top: 6rpx;
  font-size: 24rpx;
  color: #999;
}

.section {
  margin-top: 20rpx;
  background: #fff;
}

.cell {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 28rpx 30rpx;
  border-bottom: 1rpx solid #eee;
}

.cell-text {
  font-size: 28rpx;
  color: #333;
}

.logout-wrapper {
  padding: 40rpx 30rpx;
}

.logout-btn {
  width: 100%;
  background: #ff4d4f;
  color: #fff;
  border: none;
  border-radius: 12rpx;
}

.recent-section {
  margin-top: 20rpx;
  background: #fff;
  padding: 30rpx 0;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30rpx 20rpx 30rpx;
}

.section-title {
  font-size: 32rpx;
  color: #333;
  font-weight: 600;
}

.more-btn {
  font-size: 24rpx;
  color: #007AFF;
}

.recent-list {
  white-space: nowrap;
  padding: 0 30rpx;
}

.recent-item {
  display: inline-block;
  width: 200rpx;
  margin-right: 20rpx;
  vertical-align: top;
  position: relative;
}

.recent-content {
  cursor: pointer;
  position: relative;
}

.recent-cover {
  width: 200rpx;
  height: 200rpx;
  border-radius: 12rpx;
  margin-bottom: 12rpx;
}

.recent-title {
  display: block;
  font-size: 26rpx;
  color: #333;
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-bottom: 6rpx;
}

.recent-artist {
  display: block;
  font-size: 22rpx;
  color: #999;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.recent-delete {
  position: absolute;
  top: 8rpx;
  right: 8rpx;
  width: 40rpx;
  height: 40rpx;
  background: rgba(0, 0, 0, 0.6);
  border: none;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.recent-item:hover .recent-delete {
  opacity: 1;
}

.delete-icon {
  width: 24rpx;
  height: 24rpx;
}

.recent-play-overlay {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 60rpx;
  height: 60rpx;
  background: rgba(0, 0, 0, 0.7);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.recent-play-icon {
  width: 32rpx;
  height: 32rpx;
}
</style>